import {
    _decorator,
    Collider,
    Component,
    EventTouch,
    ICollisionEvent,
    resources,
    ParticleSystem,
    instantiate,
    Prefab,
    Vec3,
    Node
} from 'cc';
import {PlayerViewModel} from "db://assets/Scripts/MVC/Player/PlayerViewModel";
import {PlayerUiState} from "db://assets/Scripts/MVC/Player/PlayerUiState";
import {CollisionGroup} from "db://assets/Scripts/Common/CollisionGroup";
import {EventManager} from "db://assets/Scripts/Common/EventManager";
import {EventType} from "db://assets/Scripts/Common/EventType";
import {NodePath} from "db://assets/Scripts/Common/NodePath";
import {AudioManager} from "db://assets/Scripts/Common/AudioManager";
import {AudioPath} from "db://assets/Scripts/Common/AudioPath";
import {PoolManager} from "db://assets/Scripts/framework/PoolManager";
import {ModelPath} from "db://assets/Scripts/Common/ModelPath";
import {EffectPath} from "db://assets/Scripts/Common/EffectPath";

const {ccclass, property} = _decorator;

/**
 * 玩家控制器
 * 1.玩家滑动屏幕控制飞机移动，且游戏正式开始
 * 2.飞机可以飞到屏幕任意位置
 * 3.飞机每0.3秒向前发射一次子弹
 */
@ccclass('PlayerController')
export class PlayerController extends Component {
    /**
     * 玩家ViewModel
     */
    public viewModel: PlayerViewModel = new PlayerViewModel();
    /**
     * 玩家UiState
     */
    public uiState: PlayerUiState = this.viewModel.uiState;

    onLoad() {
        // 初始化碰撞器
        this.uiState.collider = this.getComponent(Collider);

        // 为玩家创建血条
        this.createHPBar();
        // 为飞机创建尾焰
        this.createTailFlame();
    }

    onEnable() {
        // 添加碰撞检测
        this.uiState.collider.on('onCollisionEnter', this.onCollisionEnter, this);
    }

    onDisable() {
        // 移除碰撞检测
        this.uiState.collider.off('onCollisionEnter', this.onCollisionEnter, this);
    }

    start() {

    }

    update(deltaTime: number) {

    }

    /**
     * 持续触摸
     *
     * @param event 触摸事件
     */
    private touchMove(event: EventTouch) {
        // 记录上一次触摸的位置
        // 和这一次触摸的位置
        // 取差值
        // 得到移动方向
        // 计算移动速度

        // 触摸距离
        let delta = event.getDelta();
        // 获取节点位置
        let position = this.node.position;
        // 设置节点位置
        // 0.01 是为了防止飞机移动过快
        this.node.setPosition(position.x + 0.01 * this.uiState.speed * delta.x, position.y, position.z - 0.01 * this.uiState.speed * delta.y);
    }

    /**
     * 碰撞检测
     *
     * @param event 碰撞事件
     */
    private onCollisionEnter(event: ICollisionEvent) {
        // 获取另一个碰撞器的分组
        let otherGroup = event.otherCollider.getGroup();
        // 当碰到敌方子弹或敌方飞机时
        if (otherGroup === CollisionGroup.ENEMY_BULLET || otherGroup === CollisionGroup.ENEMY_PLANE) {
            // 显示生命条
            if (!this.uiState.hpBarNode.active) {
                this.uiState.hpBarNode.active = true;
            }
            // 生命值-1
            if (this.uiState.hp > 0) {
                this.uiState.hp -= 1;
            }
            // 检测玩家是否死亡
            this.checkDied();
        }

        // 道具
        if (otherGroup === CollisionGroup.PROP) {
            // console.log(`获得道具：${event.otherCollider.node.name}`);
        }
    }

    /**
     * 检测玩家是否死亡
     */
    private checkDied() {
        // 当玩家死亡时
        if (!this.viewModel.isLive()) {
            // 播放死亡声音
            AudioManager.getInstance().playSound(AudioPath.playerDiedSound);
            // 播放死亡动画
            this.playDiedEffect(this.node.parent, this.node.position);
            // 销毁节点
            this.node.destroy();
            // 隐藏游戏面板，显示游戏结束面板
            EventManager.emit(EventType.MENU_VISIBILITY, NodePath.GAME_MENU, false);
            EventManager.emit(EventType.MENU_VISIBILITY, NodePath.OVER_MENU, true);
        }
    }

    /**
     * 播放死亡动画
     */
    private playDiedEffect(parent: Node, position: Vec3) {
        resources.load(EffectPath.explode, Prefab, (err, data) => {
            if (err) {
                console.log("爆炸特效加载失败！");
                return;
            }

            // 爆炸节点
            const explodeNode = instantiate(data);
            // 设置父节点
            explodeNode.setParent(parent);
            // 设置位置
            explodeNode.setPosition(position);
        });
    }

    /**
     * 创建生命条
     */
    private createHPBar() {
        resources.load(ModelPath.playerHP, Prefab, (err, data) => {
            if (err) {
                console.log("血条模型加载失败！");
                return;
            }

            // 实例化血条节点
            this.uiState.hpBarNode = instantiate(data);
            // 设置父节点
            this.uiState.hpBarNode.setParent(this.node);
            // 设置位置
            this.uiState.hpBarNode.setPosition(0, 0, -1);
            // 隐藏生命条
            this.uiState.hpBarNode.active = false;
        });
    }

    /**
     * 为飞机添加尾焰
     */
    private createTailFlame() {
        resources.load(EffectPath.tailFlame, Prefab, (err, data) => {
            if (err) {
                console.log("尾焰特效加载失败！");
                return;
            }

            // 尾焰
            const tailFlameNode = instantiate(data);
            // 设置父节点
            tailFlameNode.setParent(this.node);
            // 设置位置
            tailFlameNode.setPosition(0, 0, 1);
        });
    }
}